package com.appspot.bibtable.servlet;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appspot.bibtable.PMF;
import com.appspot.bibtable.UrlCollection;
import com.appspot.bibtable.model.UserInfo;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class RegisterMembershipServlet extends HttpServlet
{
	private static final Logger logger = Logger.getLogger(RegisterMembershipServlet.class.getName());

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		UserService service = UserServiceFactory.getUserService();
		if (service.isUserLoggedIn())
		{
			User user = service.getCurrentUser();
			PersistenceManager manager = PMF.get().getPersistenceManager();
			UserInfo userInfo = UserInfo.getUserInfoOf(user, manager);

			try
			{
				if (userInfo != null)
				{
					logger.warning("Registered user.");
				}
				else
				{
					userInfo = new UserInfo();
					userInfo.setKey(user);
					userInfo.setRegisteredDate(new Date());
					manager.makePersistent(userInfo);
					logger.info("New user id:" + user.getUserId() + " is now registered.");
				}
			}
			finally
			{
				manager.close();
			}
		}
		else
		{
			logger.warning("Anonymous user.");
		}

		response.sendRedirect(UrlCollection.PROFILE);
	}
}
